﻿using UnityEngine;
using UnityEditor;
using CWM.Skinn.FFD;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Renderer/Tools/Create Lattice Deformer",
            "Create a Bone Based Lattice Deformer.",
            ContextRequirements.SingleItem, 0)]
        public static void CreateLattice()
        {
            var contextItem = SkinnContext.GetContextItem();
            if (SkinnEx.IsNullOrNotInAScene(contextItem)) { SkinnContext.Finished();  return; }
            var context = contextItem.GetComponent<Renderer>();
            if (SkinnEx.IsNullOrNotInAScene(context)) { SkinnContext.Finished(); return; }

            var ffd = LatticeUtility.CreateLatticeDeformer(context.GetSharedMesh(), context.transform);
            if (!ffd) { SkinnContext.Finished(); return; }
            foreach (var transform in ffd.transform.GetAllChildren(true))
                Undo.RegisterCreatedObjectUndo(transform.gameObject, "Create Lattice Deformer");

            Undo.RecordObject(context.gameObject, "Create Lattice Deformer");
            context.gameObject.SetActive(false);
            Selection.activeGameObject = ffd.gameObject;
            SkinnContext.Finished();
        }


        [CtxMenuItem("Renderer/Tools/Create Texture Packer",
            "Create a TexturePacker for creating a texture atlas.",
            ContextRequirements.SubMeshes, 001)]
        public static void CreateTexturePacker()
        {
            var contextItem = SkinnContext.GetContextItem();
            if (SkinnEx.IsNullOrNotInAScene(contextItem)) { SkinnContext.Finished(); return; }
            var context = contextItem.GetComponent<Renderer>();
            if (SkinnEx.IsNullOrNotInAScene(context)) { SkinnContext.Finished(); return; }

            var tp = new GameObject(context.name + "_TexturePacker").AddComponent<TexturePacker>();
            tp.source = context;

            foreach (var transform in tp.transform.GetAllChildren(true))
                Undo.RegisterCreatedObjectUndo(transform.gameObject, "Create TexturePacker");

            Selection.activeGameObject = tp.gameObject;
            SkinnContext.Finished();
        }
    }
}
